/*
 * @Author: 肖思汗 
 * @Date: 2025-06-24 18:44:56 
 * @Last Modified by: xiaosihan
 * @Last Modified time: 2025-08-26 16:11:56
 */

import { View, Image } from "@tarojs/components";
import Taro from "@tarojs/taro";
import { autorun } from "mobx";
import { ReactNode, useEffect, useRef, useState } from "react";
import PageLayer from "src/components/PageLayer/PageLayer";
import userStore from "src/pages/User/userStore";
import styles from "./acceptInvitation.module.less";
import acceptInvitationApi from "./acceptInvitationApi";
import acceptInvitationStore from "./acceptInvitationStore";
import { Button } from "@nutui/nutui-react-taro";
import utils from "src/utils/utils";
import { observer } from "mobx-react-lite";
import utilsApi from "src/api/utilsApi";
import { RichText } from "@tarojs/components";
import utilsStore from "src/utils/utilsStore";

interface Iprops {
    children?: ReactNode
}

// 接受邀请
const AcceptInvitation = observer((props: Iprops) => {

    const { scene, userCode, transferToken } = Taro.getCurrentInstance().router?.params || {};
    // const dom = useRef<HTMLDivElement | null>(null);
    // console.log("invite_imgs");
    // const [richText, setRichText] = useState("");
    const [imgurl, setImgurl] = useState<string>("");

    useEffect(() => {
        utilsApi.queryPropertyByTitle("invite_imgs").then((invite_imgs) => {
            setImgurl(utils.randArray(invite_imgs));
        });
    }, []);

    // 确认邀请
    const onConfirm = async () => {
        userStore.awaitLogined().then(async () => {

            // 邀请码里面的参数是 scene  直接分享 参数是 userCode
            console.log("scene", scene, "userCode", userCode);

            let user_code = userCode;

            if (scene) {
                const decodedStr = decodeURIComponent(scene); // 步骤1
                const [key, value] = decodedStr.split('=');   // 步骤2
                const resultObj = { [key]: value };           // 步骤3
                console.log(resultObj);
                const { userCode } = resultObj;
                user_code = userCode;
            }


            let result: any;

            if (user_code) {
                await acceptInvitationApi.linkParentUserCode(user_code).then((res) => {
                    // console.log(1, res);
                    // setTimeout(() => {
                    //     Taro.switchTab({ url: '/pages/Index/Index' });
                    // }, 2000);
                    result = res;
                }).catch((err) => {
                    console.log(err);
                }).finally(async () => {
                    // 如果有转赠码
                    if (transferToken) {
                        Taro.redirectTo({
                            url: `/subPages/MyCoupons/MyCoupons?transferToken=${transferToken}`,
                        });
                    } else {
                        if (result && result.msg.includes('券')) {
                            Taro.showToast({
                                title: "获得一张优惠券",
                                icon: 'none',
                            });
                        }
                        await new Promise(resolve => setTimeout(resolve, 2000));
                        Taro.switchTab({
                            url: '/pages/Index/Index',
                        });
                    }
                })
            }


        });
    };

    return (
        <PageLayer
            title={transferToken ? "领取优惠券" : "开启定制"}
            className={styles.acceptInvitation}
            hasTabBar={false}
        >
            {/* <RichText
                className="ql-editor"
                nodes={richText.replace(/<img([^>]*)>/g, '<img style="max-width:100%;height:auto;" $1>')}
            /> */}
            <Image
                mode="widthFix"
                style={{
                    width: "100%"
                }}
                src={utils.ossSuffix(imgurl)}
            />

            <View
                className={styles.bottomBtns}
                style={{
                    paddingBottom: utilsStore.safeAreaBottom || utils.rpx2px(20)
                }}
            >
                <Button
                    onClick={onConfirm}
                    block
                    type="primary"
                    className={styles.confirmBtn}
                >{transferToken ? "领取优惠券" : "开启定制"}</Button>
            </View>

        </PageLayer>
    );
});

export default AcceptInvitation;